package top.itpath.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import top.itpath.admin.entity.SysRole;
import top.itpath.admin.entity.SysUserRole;
import top.itpath.admin.mapper.SysRoleMapper;
import top.itpath.admin.mapper.SysUserRoleMapper;
import top.itpath.admin.service.ISysUserRoleService;

import javax.transaction.Transactional;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author zhaomengru
 * create by  2023/10/11 - 13:59
 */
@Service
@RequiredArgsConstructor
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements ISysUserRoleService {

    private final SysRoleMapper sysRoleMapper;

    @Override
    public List<SysRole> listUserRole(Long userId) {
        List<SysUserRole> list = CollectionUtil.emptyIfNull(this.lambdaQuery().eq(SysUserRole::getUserId, userId).list());
        Set<Long> roleId = list.stream().map(SysUserRole::getRoleId).collect(Collectors.toSet());
        if (CollectionUtil.isEmpty(roleId)) {
            return List.of();
        }
        return sysRoleMapper.selectBatchIds(roleId);
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public void setRole(Long userId, Collection<Long> roleIds) {
        if (CollectionUtil.isEmpty(roleIds)) {
            return;
        }
        this.lambdaUpdate().eq(SysUserRole::getUserId, userId).remove();
        List<SysUserRole> sysUserRoles = roleIds.stream().map(item -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userId);
            sysUserRole.setRoleId(item);
            return sysUserRole;
        }).collect(Collectors.toList());
        this.saveBatch(sysUserRoles);
    }
}
